package com.ebanma.cloud.usertestall.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ebanma.cloud.usertestall.domain.common.PageQuery;
import com.ebanma.cloud.usertestall.domain.common.PageResult;
import com.ebanma.cloud.usertestall.domain.dto.UserDTO;
import com.ebanma.cloud.usertestall.domain.dto.UserQueryDTO;
import com.ebanma.cloud.usertestall.domain.entity.UserPO;
import com.ebanma.cloud.usertestall.mapper.UserMapper;
import com.ebanma.cloud.usertestall.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public int save(UserDTO userDTO) {
        UserPO userPO = new UserPO();

        // TODO 浅拷贝 属性名相同才能拷贝  
        BeanUtils.copyProperties(userDTO, userPO);

        return userMapper.insert(userPO);

    }

    @Override
    public int update(Long id, UserDTO userDTO) {
        UserPO userPO = new UserPO();

        BeanUtils.copyProperties(userDTO, userPO);

        userPO.setId(id);

        return userMapper.updateById(userPO);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteById(id);
    }


    @Override
    public PageResult<List<UserDTO>> query(PageQuery<UserQueryDTO> pageQuery) {
        Page page = new Page(pageQuery.getPageNumber(), pageQuery.getPageSize());

        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(pageQuery.getQuery(), userPO);
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>(userPO);

        IPage<UserPO> userPage = userMapper.selectPage(page, queryWrapper);

        PageResult<List<UserDTO>> pageResult = new PageResult();
        pageResult.setPageNumber((int)userPage.getCurrent());
        pageResult.setPageSize((int)userPage.getSize());
        pageResult.setTotal(userPage.getTotal());

        List<UserDTO> userDTOList = Optional.ofNullable(userPage.getRecords()).orElseGet(ArrayList::new).stream()
            .map(user -> {
                UserDTO userDTO = new UserDTO();
                BeanUtils.copyProperties(user, userDTO);
                return userDTO;
            }).collect(Collectors.toList());

        pageResult.setRecords(userDTOList);

        return pageResult;
    }


}
